﻿using BLL;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace OAElectronics.Controllers
{
    public class UserController : Controller
    {
        private readonly SystemBLL _systemBLL;
        
        public UserController(SystemBLL systemBLL)
        {
            _systemBLL = systemBLL;
        }
        //主页
        [Authorize(Policy = "开发部")]
        //[Authorize(Roles = "")]
        public IActionResult Index()
        {
            return View();
        }
        //登录
        public IActionResult login()
        {
            return View();
        }
        [Authorize(Policy = "开发部")]
        [Authorize(Roles = "总经理")]
        public IActionResult Userl()
        {
            return View();
        }
        [Authorize(Policy = "开发部")]
        [Authorize(Roles = "总经理")]
        public IActionResult Add()
        {
            return View();
        }
        public IActionResult Tu() {
           HttpContext.SignOutAsync();
           return  Redirect("/User/Index");
        }
        [Authorize(Policy = "开发部")]
        [Authorize(Roles = "总经理")]
        [HttpGet]
        public List<Personnel> Uases()
        {
            List <Personnel> p = _systemBLL.personnels().ToList();
            return p;
        }
        [Authorize(Policy = "开发部")]
        [Authorize(Roles = "总经理")]
        public int AddUser(Personnel p)
        {
            return _systemBLL.Add(p);

        }
        [Authorize(Policy = "开发部")]
        [Authorize(Roles = "总经理")]
        public int uPersonnel([FromBody] Personnel p) 
        {
            return _systemBLL.upersonnel(p.staff_ID, p.Role_ID);
        }
        public List<Role> Roles()
        {
            List<Role> r = _systemBLL.Roless().ToList();
            return r;
        }
        [HttpPost]
        public string Loginl([FromBody] Personnel ps)
        {
            
            var list = _systemBLL.Login(ps.username, ps.password).FirstOrDefault();
            if (list == null) return null;
            var c = new List<Claim>
               {

                 new Claim(type:"id",value:list.staff_ID.ToString()),//姓名

               new Claim(ClaimTypes.Name,value:list.staff_NAME),//姓名
               new Claim(type:"id",value:list.staff_ID.ToString()),
               new Claim(type:"staff_CODE",value:list.staff_CODE),//工号
               new Claim(type:"Time",value:DateTime.Now.ToString()),//登录时间
               new Claim (ClaimTypes.Role,list.Role.Role_Name)//角色
               };
            var identiy = new ClaimsIdentity(c, authenticationType: "identiy");
            HttpContext.SignInAsync(principal: new ClaimsPrincipal(identiy));
            
            return list.staff_NAME; 
        }
    }
}
